<template>
  <div class="search-date">
    <slot name="title">
      <div class="date-title">请至少选择一个日期</div>
    </slot>
    <div class="date-content">
      <div class="date-start">
        <div class="tip-title">开始日期</div>
        <a-date-picker
          allow-clear
          value-format="X"
          v-model="start"
          type="date"
          :show-now-btn="false"
          :disabled-date="startDisabledDateFn"
          placeholder="请选择日期">
          <template #prefix>
            <img :src="datePrefix" alt="" width="16" height="16" />
          </template>
        </a-date-picker>
      </div>
      <div class="date-end">
        <div class="tip-title">结束日期</div>

        <a-date-picker
          allow-clear
          value-format="X"
          :model-value="end"
          :show-now-btn="false"
          :disabled-date="endDisabledDateFn"
          placeholder="请选择日期"
          @update:model-value="onUpdateEnd">
          <template #prefix>
            <img :src="datePrefix" alt="" width="16" height="16" />
          </template>
        </a-date-picker>
      </div>
    </div>
    <div class="search-popover-footer">
      <a-button @click="handleCancel" size="small">取消</a-button>
      <a-button
        @click="handleOk"
        type="primary"
        size="small"
        :disabled="!start && !end"
        >确定</a-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { ref } from 'vue'

import datePrefix from '../icons/date-prefix.svg'
const props = defineProps<{
  startDisabledDate?: () => any
  endDisabledDate?: () => any
}>()

const emit = defineEmits<{
  ok: [value: number[]]
  cancel: []
}>()

defineSlots<{
  title(): any
}>()

const start = ref()
const end = ref()

function onClear() {
  start.value = ''
  end.value = ''
}

function handleCancel() {
  emit('cancel')
  onClear()
}

function startDisabledDateFn(value?: Date) {
  if (end.value) {
    const endDate = dayjs.unix(end.value)
    const startDate = dayjs(value)
    return (
      !startDate.isBefore(endDate.add(1, 'day')) ||
      props.startDisabledDate?.(value)
    )
  }
  return props.startDisabledDate?.(value)
}

function endDisabledDateFn(value?: Date) {
  if (start.value) {
    const startDate = dayjs.unix(start.value ?? 0)
    const endDate = dayjs(value)
    return (
      !endDate.isAfter(startDate.subtract(1, 'day')) ||
      props.endDisabledDate?.(value)
    )
  }
  return props.endDisabledDate?.(value)
}

function onUpdateEnd(val: string) {
  end.value = !val ? val : String(+val + 86399)
}

function handleOk() {
  emit('ok', [start.value, end.value])
  onClear()
}
</script>
